package org.sidora.strata.category;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.UIManager;
import org.openide.ErrorManager;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.sidora.core.Category;
import org.sidora.core.Describer;
import org.sidora.core.Document;
import org.sidora.core.Feature;
import org.sidora.core.Photo;
import org.sidora.core.Site;
import org.sidora.core.context.BuildedContext;
import org.sidora.core.context.Context;
import org.sidora.core.context.DeposedElement;
import org.sidora.core.context.DevastatedContext;
import org.sidora.core.context.EmptyedContext;
import org.sidora.core.context.Stratum;
import org.sidora.core.context.Surface;
import org.sidora.core.context.TechnicalContext;
import org.sidora.core.util.AbstractInventory;
import org.sidora.core.util.ParameterCollector;
import org.sidora.strata.Storage;

/**
 * CategoryFormTopComponent wich displays something
 * @author Enric Tartera, Juan Manuel Gimeno, Roger Masgoret
 * @version 1.0
 */
final class CategoryFormTopComponent extends TopComponent {

    private static CategoryFormTopComponent instance;
    /** path to the icon used by the component and its open action */
    static final String ICON_PATH = "org/sidora/resources/category16.png";
    private static final String PREFERRED_ID = "CategoryFormTopComponent";

    private CategoryFormTopComponent() {
        System.setProperty(
                "Quaqua.tabLayoutPolicy", "wrap");

        // set the Quaqua Look and Feel in the UIManager
        try {
            UIManager.setLookAndFeel(
                    "ch.randelshofer.quaqua.QuaquaLookAndFeel");
        // set UI manager properties here that affect Quaqua

        } catch (Exception e) {
            // take an appropriate action here
        }

        initComponents();
        setName(NbBundle.getMessage(CategoryFormTopComponent.class, "CTL_CategoryFormTopComponent"));
        setToolTipText(NbBundle.getMessage(CategoryFormTopComponent.class, "HINT_CategoryFormTopComponent"));
        setIcon(Utilities.loadImage(ICON_PATH, true));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jListFields = new javax.swing.JList();
        jListFields.putClientProperty(

            "Quaqua.List.style", "striped"

        );
        jLabel1 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jListDescriber = new javax.swing.JList();
        jListDescriber.putClientProperty(

            "Quaqua.List.style", "striped"

        );
        jScrollPane3 = new javax.swing.JScrollPane();
        jListCategory = new javax.swing.JList();
        jListCategory.putClientProperty(

            "Quaqua.List.style", "striped"

        );
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jButtonDelType = new javax.swing.JButton();
        jButtonDelType.putClientProperty(

            "Quaqua.Button.style", "placard"

        );
        jButtonAddType = new javax.swing.JButton();
        jButtonAddType.putClientProperty(

            "Quaqua.Button.style", "placard"

        );
        jButtonDelCategory = new javax.swing.JButton();
        jButtonDelCategory.putClientProperty(

            "Quaqua.Button.style", "placard"

        );
        jButtonAddCategory = new javax.swing.JButton();
        jButtonAddCategory.putClientProperty(

            "Quaqua.Button.style", "placard"

        );
        jPanel1 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jTextFieldDescriberLabel = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        jTextFieldCategoryValue = new javax.swing.JTextField();
        jComboBoxClass = new javax.swing.JComboBox();
        jPanel3 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton1.putClientProperty(

            "Quaqua.Button.style", "placard"

        );
        jButton2 = new javax.swing.JButton();
        jButton2.putClientProperty(

            "Quaqua.Button.style", "placard"

        );

        jListFields.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jListFieldsValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jListFields);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, "Class");

        jListDescriber.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jListDescriberValueChanged(evt);
            }
        });
        jScrollPane2.setViewportView(jListDescriber);

        jListCategory.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jListCategoryValueChanged(evt);
            }
        });
        jScrollPane3.setViewportView(jListCategory);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, "Describer");

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, "Category");

        org.openide.awt.Mnemonics.setLocalizedText(jButtonDelType, "-");
        jButtonDelType.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDelTypeActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jButtonAddType, "+");
        jButtonAddType.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAddTypeActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jButtonDelCategory, "-");
        jButtonDelCategory.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDelCategoryActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jButtonAddCategory, "+");
        jButtonAddCategory.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAddCategoryActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Describer"));

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, "Label:");

        jTextFieldDescriberLabel.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextFieldDescriberLabelFocusLost(evt);
            }
        });
        jTextFieldDescriberLabel.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextFieldDescriberLabelKeyReleased(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel4)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jTextFieldDescriberLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 486, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel4)
                    .add(jTextFieldDescriberLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Category"));

        org.openide.awt.Mnemonics.setLocalizedText(jLabel7, "Value:");

        jTextFieldCategoryValue.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextFieldCategoryValueFocusLost(evt);
            }
        });
        jTextFieldCategoryValue.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextFieldCategoryValueKeyReleased(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel7)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jTextFieldCategoryValue, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 485, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel7)
                    .add(jTextFieldCategoryValue, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jComboBoxClass.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Stratum", "Builded", "Emptyed", "Surface", "Devastated", "Deposed", "Technical", "Document", "Photo" }));
        jComboBoxClass.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBoxClassItemStateChanged(evt);
            }
        });

        jButton1.setFont(new java.awt.Font("Lucida Grande", 0, 10));
        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sidora/resources/Save32.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(jButton1, "Save");
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        jButton2.setFont(new java.awt.Font("Lucida Grande", 0, 10));
        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sidora/resources/Load32.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(jButton2, "Load");
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 73, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jButton2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 73, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 71, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jButton2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 71, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(139, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, jComboBoxClass, 0, 158, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 158, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel1))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabel2)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                .add(jButtonAddType)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(jButtonDelType))
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                .add(3, 3, 3)
                                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabel3)
                            .add(layout.createSequentialGroup()
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                    .add(layout.createSequentialGroup()
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                        .add(jButtonAddCategory)
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                        .add(jButtonDelCategory))
                                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                                        .add(jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 146, Short.MAX_VALUE)
                                        .add(10, 10, 10)))
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .add(23, 23, 23)))
                .addContainerGap())
        );

        layout.linkSize(new java.awt.Component[] {jComboBoxClass, jScrollPane1}, org.jdesktop.layout.GroupLayout.HORIZONTAL);

        layout.linkSize(new java.awt.Component[] {jPanel1, jPanel2}, org.jdesktop.layout.GroupLayout.HORIZONTAL);

        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(jLabel2)
                    .add(jLabel3))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE)
                    .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(jComboBoxClass, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE)))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButtonDelType)
                    .add(jButtonAddType)
                    .add(jButtonDelCategory)
                    .add(jButtonAddCategory))
                .add(15, 15, 15)
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(20, 20, 20))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jComboBoxClassItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxClassItemStateChanged
        fillComboBox();
    }//GEN-LAST:event_jComboBoxClassItemStateChanged

    private void fillComboBox() {
        String string = (String) jComboBoxClass.getSelectedItem();
        DefaultListModel fieldModel = new DefaultListModel();
        if (string.equals("Stratum")) {
            fieldModel.addElement("Composition");
            fieldModel.addElement("Colour");
            fieldModel.addElement("Compaction");
            fieldModel.addElement("Inclusions");
            fieldModel.addElement("Measures");
            fieldModel.addElement("Slope");
            fieldModel.addElement("Interpreted Type");
        } else if (string.equals("Builded")) {
            fieldModel.addElement("Building Technique");
            fieldModel.addElement("Building Material");
            fieldModel.addElement("Bonding Material");
            fieldModel.addElement("Coursing");
            fieldModel.addElement("Interpreted Type");

        } else if (string.equals("Context")) {
            fieldModel.addElement("Taken Material Remains");
            fieldModel.addElement("Digging Method");
            fieldModel.addElement("Intrusion Risk");
            fieldModel.addElement("Location in Sector");

        } else if (string.equals("Deposed")) {
            fieldModel.addElement("Deposed Element");
            fieldModel.addElement("Isolated");
            fieldModel.addElement("Primary");
            fieldModel.addElement("Interpreted Type");

        } else if (string.equals("Technical")) {
            fieldModel.addElement("Task");
            fieldModel.addElement("Interpreted Type");

        } else if (string.equals("Surface")) {
            fieldModel.addElement("Activity Traces");
            fieldModel.addElement("Interpreted Type");

        } else if (string.equals("Devastated")) {
            fieldModel.addElement("Destruction Traces");
            fieldModel.addElement("Interpreted Type");

        } else if (string.equals("Emptyed")) {
            fieldModel.addElement("Plan");
            fieldModel.addElement("Section");
            fieldModel.addElement("Interpreted Type");

        } else if (string.equals("Document")) {
            fieldModel.addElement("Type");

        } else if (string.equals("Photo")) {
            fieldModel.addElement("Support");
            fieldModel.addElement("View");

        } else if (string.equals("Feature")) {
            fieldModel.addElement("FeatureType");
        }

        jListFields.setModel(fieldModel);
    }

    private void jTextFieldCategoryValueFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldCategoryValueFocusLost
        saveCategory();
    }//GEN-LAST:event_jTextFieldCategoryValueFocusLost

    private void saveCategory() {
        if (categorySelected != null) {
            categorySelected.setValue(jTextFieldCategoryValue.getText());
            AbstractInventory.setObject(categorySelected);
        }
    }

    private void jListCategoryValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListCategoryValueChanged

        saveCategory();
        categorySelected = (Category) jListCategory.getSelectedValue();
        fillCategoryItems();

    }//GEN-LAST:event_jListCategoryValueChanged

    private void jTextFieldDescriberLabelFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldDescriberLabelFocusLost
        saveDescriber();
    }//GEN-LAST:event_jTextFieldDescriberLabelFocusLost

    private void saveDescriber() {
        if (describerSelected != null) {
            describerSelected.setLabel(jTextFieldDescriberLabel.getText());
            AbstractInventory.setObject(describerSelected);
        }
    }

    private void jListDescriberValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListDescriberValueChanged

        saveDescriber();
        describerSelected = (Describer) jListDescriber.getSelectedValue();
        fillCategoryList();
        fillDescriberItems();

    }//GEN-LAST:event_jListDescriberValueChanged

    private void jListFieldsValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListFieldsValueChanged

        fillDescriberList();

    }//GEN-LAST:event_jListFieldsValueChanged

    private void fillDescriberList() {
        DefaultListModel describerModel = new DefaultListModel();
        ParameterCollector param = getClassField();
        Class clas = (Class) param.get("class");
        Field fiel = (Field) param.get("field");

        List<Describer> list = Describer.Inventory.getList(Storage.getSite());

        Iterator iter = list.iterator();
        while (iter.hasNext()) {
            Describer des = (Describer) iter.next();
            String s1 = des.getField().getName();
            String s2 = fiel.getName();
            if (des.getReferencedClass() == clas && s1.equals(s2)) {
                describerModel.addElement(des);
            }
        }

        jListDescriber.setModel(describerModel);
        jListCategory.setModel(new DefaultListModel());
    }

    private ParameterCollector getClassField() {
        String cla = (String) jComboBoxClass.getSelectedItem();
        String fie = (String) jListFields.getSelectedValue();
        Class clas = null;
        Field fiel = null;

        if (cla.equals("Stratum")) {
            clas = Stratum.class;

            try {
                if (fie.equals("Composition")) {
                    fiel = clas.getDeclaredField("composition");
                }
                if (fie.equals("Colour")) {
                    fiel = clas.getDeclaredField("colour");
                }
                if (fie.equals("Compaction")) {
                    fiel = clas.getDeclaredField("compaction");
                }
                if (fie.equals("Inclusions")) {
                    fiel = clas.getDeclaredField("inclusions");
                }
                if (fie.equals("Measures")) {
                    fiel = clas.getDeclaredField("measures");
                }
                if (fie.equals("Slope")) {
                    fiel = clas.getDeclaredField("slope");
                }
                if (fie.equals("Interpreted Type")) {
                    fiel = Context.class.getDeclaredField("interpretedType");
                }
            } catch (SecurityException ex) {
                ex.printStackTrace();
            } catch (NoSuchFieldException ex) {
                ex.printStackTrace();
            }
        } else if (cla.equals("Builded")) {
            clas = BuildedContext.class;

            try {
                if (fie.equals("Building Technique")) {
                    fiel = clas.getDeclaredField("buildingTechnique");
                }
                if (fie.equals("Building Material")) {
                    fiel = clas.getDeclaredField("buildingMaterial");
                }
                if (fie.equals("Bonding Material")) {
                    fiel = clas.getDeclaredField("bondingMaterial");
                }
                if (fie.equals("Coursing")) {
                    fiel = clas.getDeclaredField("coursing");
                }
                if (fie.equals("Interpreted Type")) {
                    fiel = Context.class.getDeclaredField("interpretedType");
                }
            } catch (SecurityException ex) {
                ex.printStackTrace();
            } catch (NoSuchFieldException ex) {
                ex.printStackTrace();
            }
        } else if (cla.equals("Context")) {
            clas = Context.class;

            try {
                if (fie.equals("Taken Material Remains")) {
                    fiel = clas.getDeclaredField("takenMaterialRemains");
                }
                if (fie.equals("Digging Method")) {
                    fiel = clas.getDeclaredField("diggingMethod");
                }
                if (fie.equals("Intrusion Risk")) {
                    fiel = clas.getDeclaredField("intrusionRisk");
                }
                if (fie.equals("Location in Sector")) {
                    fiel = clas.getDeclaredField("locationInSector");
                }
            } catch (SecurityException ex) {
                ex.printStackTrace();
            } catch (NoSuchFieldException ex) {
                ex.printStackTrace();
            }
        } else if (cla.equals("Deposed")) {
            clas = DeposedElement.class;

            try {
                if (fie.equals("Deposed Element")) {
                    fiel = clas.getDeclaredField("deposedElement");
                }
                if (fie.equals("Isolated")) {
                    fiel = clas.getDeclaredField("isolated");
                }
                if (fie.equals("Primary")) {
                    fiel = clas.getDeclaredField("primary");
                }
                if (fie.equals("Interpreted Type")) {
                    fiel = Context.class.getDeclaredField("interpretedType");
                }
            } catch (SecurityException ex) {
                ex.printStackTrace();
            } catch (NoSuchFieldException ex) {
                ex.printStackTrace();
            }
        } else if (cla.equals("Technical")) {
            clas = TechnicalContext.class;

            try {
                if (fie.equals("Task")) {
                    fiel = clas.getDeclaredField("task");
                }
                if (fie.equals("Interpreted Type")) {
                    fiel = Context.class.getDeclaredField("interpretedType");
                }
            } catch (SecurityException ex) {
                ex.printStackTrace();
            } catch (NoSuchFieldException ex) {
                ex.printStackTrace();
            }
        } else if (cla.equals("Surface")) {
            clas = Surface.class;

            try {
                if (fie.equals("Activity Traces")) {
                    fiel = clas.getDeclaredField("activityTraces");
                }
                if (fie.equals("Interpreted Type")) {
                    fiel = Context.class.getDeclaredField("interpretedType");
                }
            } catch (SecurityException ex) {
                ex.printStackTrace();
            } catch (NoSuchFieldException ex) {
                ex.printStackTrace();
            }
        } else if (cla.equals("Devastated")) {
            clas = DevastatedContext.class;

            try {
                if (fie.equals("Destruction Traces")) {
                    fiel = clas.getDeclaredField("destructionTraces");
                }
                if (fie.equals("Interpreted Type")) {
                    fiel = Context.class.getDeclaredField("interpretedType");
                }
            } catch (SecurityException ex) {
                ex.printStackTrace();
            } catch (NoSuchFieldException ex) {
                ex.printStackTrace();
            }
        } else if (cla.equals("Emptyed")) {
            clas = EmptyedContext.class;

            try {
                if (fie.equals("Plan")) {
                    fiel = clas.getDeclaredField("plan");
                }
                if (fie.equals("Section")) {
                    fiel = clas.getDeclaredField("section");
                }
                if (fie.equals("Interpreted Type")) {
                    fiel = Context.class.getDeclaredField("interpretedType");
                }
            } catch (SecurityException ex) {
                ex.printStackTrace();
            } catch (NoSuchFieldException ex) {
                ex.printStackTrace();
            }
        } else if (cla.equals("Document")) {
            clas = Document.class;

            try {
                if (fie.equals("Type")) {
                    fiel = clas.getDeclaredField("type");
                }
            } catch (SecurityException ex) {
                ex.printStackTrace();
            } catch (NoSuchFieldException ex) {
                ex.printStackTrace();
            }
        } else if (cla.equals("Photo")) {
            clas = Photo.class;

            try {
                if (fie.equals("View")) {
                    fiel = clas.getDeclaredField("view");
                }
                if (fie.equals("Support")) {
                    fiel = clas.getDeclaredField("support");
                }
            } catch (SecurityException ex) {
                ex.printStackTrace();
            } catch (NoSuchFieldException ex) {
                ex.printStackTrace();
            }
        } else if (cla.equals("Feature")) {
            clas = Feature.class;

            try {
                if (fie.equals("FeatureType")) {
                    fiel = clas.getDeclaredField("featureType");
                }
            } catch (SecurityException ex) {
                ex.printStackTrace();
            } catch (NoSuchFieldException ex) {
                ex.printStackTrace();
            }
        }


        ParameterCollector param = new ParameterCollector();
        param.put("class", clas);
        param.put("field", fiel);
        return param;
    }

    private void jButtonAddCategoryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddCategoryActionPerformed
        addCategory();
        fillCategoryList();

    }//GEN-LAST:event_jButtonAddCategoryActionPerformed

    private void jButtonDelCategoryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDelCategoryActionPerformed
        delCategory();
        fillCategoryList();
    }//GEN-LAST:event_jButtonDelCategoryActionPerformed

    private void jButtonAddTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddTypeActionPerformed
        addDescriber();
        fillDescriberList();
    }//GEN-LAST:event_jButtonAddTypeActionPerformed

    private void jButtonDelTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDelTypeActionPerformed
        delDescriber();
        fillDescriberList();
    }//GEN-LAST:event_jButtonDelTypeActionPerformed

private void jTextFieldDescriberLabelKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldDescriberLabelKeyReleased
    if (evt.isActionKey()) {
        saveDescriber();
    }

}//GEN-LAST:event_jTextFieldDescriberLabelKeyReleased

private void jTextFieldCategoryValueKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldCategoryValueKeyReleased
    if (evt.isActionKey()) {
        saveCategory();
    }
}//GEN-LAST:event_jTextFieldCategoryValueKeyReleased
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButtonAddCategory;
    private javax.swing.JButton jButtonAddType;
    private javax.swing.JButton jButtonDelCategory;
    private javax.swing.JButton jButtonDelType;
    private javax.swing.JComboBox jComboBoxClass;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JList jListCategory;
    private javax.swing.JList jListDescriber;
    private javax.swing.JList jListFields;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextField jTextFieldCategoryValue;
    private javax.swing.JTextField jTextFieldDescriberLabel;
    // End of variables declaration//GEN-END:variables
    Describer.Inventory describerInventory = new Describer.Inventory();
    Category.Inventory categoryInventory = new Category.Inventory();
    Describer describerSelected;
    Category categorySelected;

    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link findInstance}.
     */
    public static synchronized CategoryFormTopComponent getDefault() {
        if (instance == null) {
            instance = new CategoryFormTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the CategoryFormTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized CategoryFormTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            ErrorManager.getDefault().log(ErrorManager.WARNING, "Cannot find CategoryForm component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof CategoryFormTopComponent) {
            return (CategoryFormTopComponent) win;
        }
        ErrorManager.getDefault().log(ErrorManager.WARNING, "There seem to be multiple components with the '" + PREFERRED_ID + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    public void componentOpened() {
        fillClasses();
    }

    public void componentClosed() {
        // TODO add custom code on component closing
    }

    /** replaces this in object stream */
    public Object writeReplace() {
        return new ResolvableHelper();
    }

    protected String preferredID() {
        return PREFERRED_ID;
    }

    final static class ResolvableHelper implements Serializable {

        private static final long serialVersionUID = 1L;

        public Object readResolve() {
            return CategoryFormTopComponent.getDefault();
        }
    }

    private void addDescriber() {

        ParameterCollector param = getClassField();

        Site site = Storage.getSite();

        param.put("label", "New describer");
        param.put("site", site);
        Describer type = null;

        try {
            type = describerInventory.getNewObject(param);
        //type = (CategoryType) InventoryPool.getInventory("CategoryType").getNewObject(param);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Field field = type.getField();
        Class clas = type.getReferencedClass();
        String label = type.getLabel();
        Site asite = type.getSite();


        AbstractInventory.setObject(type);
    }

    private void delDescriber() {
        //TODO mirar de borrar les categories en cascada
        describerSelected = (Describer) jListDescriber.getSelectedValue();
        if (describerSelected != null) {
            AbstractInventory.deleteObject(describerSelected);
            describerSelected = null;
        }
    }

    private void addCategory() {
        Describer categoryType = (Describer) jListDescriber.getSelectedValue();
        ParameterCollector param = new ParameterCollector();

        if (categoryType != null) {
            param.put("value", "New category");
            param.put("type", categoryType);

            Category category = null;
            try {
                category = categoryInventory.getNewObject(param);
            //type = (CategoryType) InventoryPool.getInventory("CategoryType").getNewObject(param);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



            AbstractInventory.setObject(category);
        }
    }

    private void delCategory() {
        categorySelected = (Category) jListCategory.getSelectedValue();
        if (categorySelected != null) {
            AbstractInventory.deleteObject(categorySelected);
            categorySelected = null;
        }
    }

    private void fillCategoryList() {
        Describer describer = (Describer) jListDescriber.getSelectedValue();
        DefaultListModel categoryModel = new DefaultListModel();

        if (describer != null) {
            Category cat;

            List<Category> list = Category.Inventory.getList(describer);
            Iterator<Category> iter = list.iterator();

            while (iter.hasNext()) {
                Category category = (Category) iter.next();
                if (category != null) {
                    categoryModel.addElement(category);

                }
            //fillCatList(null);
            }
        }
        jListCategory.setModel(categoryModel);
        fillCategoryItems();
    }

    public void fillCategoryItems() {
        categorySelected = (Category) jListCategory.getSelectedValue();
        if (categorySelected != null) {
            jTextFieldCategoryValue.setText(categorySelected.toString());
            jTextFieldCategoryValue.select(0, categorySelected.toString().length());
            jTextFieldCategoryValue.requestFocus();
        } else {
            emptyCategoryItems();
        }
    }

    public void fillDescriberItems() {
        describerSelected = (Describer) jListDescriber.getSelectedValue();
        if (describerSelected != null) {
            jTextFieldDescriberLabel.setText(describerSelected.getLabel());
            jTextFieldDescriberLabel.select(0, jTextFieldDescriberLabel.toString().length());
            jTextFieldDescriberLabel.requestFocus();
        }
    }

    public void emptyCategoryItems() {
        jTextFieldCategoryValue.setText("");
    }

    public void emptyDescriberItems() {
        jTextFieldDescriberLabel.setText("");
    }

    public void fillClasses() {
        DefaultComboBoxModel fieldModel = new DefaultComboBoxModel();
        fieldModel.addElement("Feature");
        fieldModel.addElement("Stratum");
        fieldModel.addElement("Builded");
        fieldModel.addElement("Context");
        fieldModel.addElement("Deposed");
        fieldModel.addElement("Technical");
        fieldModel.addElement("Surface");
        fieldModel.addElement("Devastated");
        fieldModel.addElement("Emptyed");
        fieldModel.addElement("Document");
        fieldModel.addElement("Photo");

        jComboBoxClass.setModel(fieldModel);
    }
}
